package com.example.msgsendmail;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

public class SMSReceiver extends BroadcastReceiver {
    private static final String TAG = "SMSReceiver";
    private static boolean serviceRunning = false;

    public static void setServiceRunning(boolean running) {
        serviceRunning = running;
    }

    public static boolean isServiceRunning() {
        return serviceRunning;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (!serviceRunning) {
            Log.d(TAG, "服务未启动，忽略短信");
            return;
        }

        String action = intent.getAction();
        Log.d(TAG, "收到广播: " + action);
        
        if ("android.provider.Telephony.SMS_RECEIVED".equals(action) ||
            "android.provider.Telephony.SMS_DELIVER".equals(action) ||
            "android.provider.Telephony.SMS_NOTIFICATION_RECEIVED".equals(action) ||
            "android.provider.Telephony.SMS_CB_RECEIVED".equals(action) ||
            "android.provider.Telephony.WAP_PUSH_RECEIVED".equals(action) ||
            "android.provider.Telephony.DATA_SMS_RECEIVED".equals(action) ||
            "android.provider.Telephony.SMS_SERVICE_CATEGORY_PROGRAM_DATA_RECEIVED".equals(action)) {
            
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                try {
                    Object[] pdus = (Object[]) bundle.get("pdus");
                    String format = bundle.getString("format");

                    if (pdus != null) {
                        StringBuilder fullMessageBody = new StringBuilder();
                        String sender = null;
                        long timestamp = 0;
                        
                        for (Object pdu : pdus) {
                            SmsMessage smsMessage;
                            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                                smsMessage = SmsMessage.createFromPdu((byte[]) pdu, format);
                            } else {
                                smsMessage = SmsMessage.createFromPdu((byte[]) pdu);
                            }

                            if (smsMessage != null) {
                                if (sender == null) {
                                    sender = smsMessage.getDisplayOriginatingAddress();
                                    timestamp = smsMessage.getTimestampMillis();
                                }
                                fullMessageBody.append(smsMessage.getMessageBody());
                            }
                        }
                        
                        if (sender != null) {
                            String messageBody = fullMessageBody.toString();
                            
                            // 记录接收到的短信
                            Log.d(TAG, "接收到短信 - 发送者: " + sender + ", 内容: " + messageBody);

                            // 更新主界面日志

                            // 转发短信到邮箱
                            forwardSmsToEmail(sender, messageBody, timestamp);
                        }
                    }
                } catch (Exception e) {
                    Log.e(TAG, "处理短信时出错: " + e.getMessage(), e);
                }
            }
        }
    }

    private void forwardSmsToEmail(String sender, String messageBody, long timestamp) {
        try {
            // 格式化时间戳
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault());
            String timeStr = sdf.format(new java.util.Date(timestamp));

            // 构建邮件主题和内容
            String subject = "短信转发 - 来自 " + sender;
            String content = "发送者: " + sender + "\n" +
                    "时间: " + timeStr + "\n" +
                    "内容: " + messageBody + "\n\n" +
                    "--- 此邮件由短信转发服务自动发送 ---";

            // 发送邮件
            EmailSender.sendEmail(subject, content, success -> {
                MainActivity mainActivity = MainActivity.getInstance();
                if (mainActivity != null) {
                    if (success) {
                        mainActivity.addLogEntry("短信已转发到邮箱");
                    } else {
                        mainActivity.addLogEntry("短信转发失败，请检查网络和邮箱配置");
                    }
                }
            });

            Log.d(TAG, "短信转发请求已发送");

        } catch (Exception e) {
            Log.e(TAG, "转发短信到邮箱时出错: " + e.getMessage(), e);
            MainActivity mainActivity = MainActivity.getInstance();
            if (mainActivity != null) {
                mainActivity.addLogEntry("转发短信到邮箱时出错: " + e.getMessage());
            }
        }
    }
}